package crp.core.resource.domain.models;

import com.qwlabs.auditing.AuditedEntity;
import com.vladmihalcea.hibernate.type.interval.PostgreSQLIntervalType;
import crp.core.shared.LifecycleStatus;
import crp.core.shared.PublicStatus;
import crp.core.shared.PublishStatus;
import crp.core.shared.Tables;
import crp.core.space.domain.models.SpaceEntity;
import crp.core.workflow.domain.models.Approval;
import io.quarkiverse.hibernate.types.json.JsonTypes;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;


@Setter
@Getter
@Entity
@TypeDef(typeClass = PostgreSQLIntervalType.class, defaultForType = Duration.class)
@Table(name = Tables.RESOURCE)
public class ResourceEntity extends AuditedEntity {
    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    private String id;
    private String name;
    private String alias;
    @Enumerated(EnumType.STRING)
    private PublicStatus publicStatus;
    @Enumerated(EnumType.STRING)
    private PublishStatus publishStatus;
    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    private SpaceEntity space;
    private Instant startAt;
    private Instant endAt;
    private Duration duration;
    @Enumerated(EnumType.STRING)
    private ResourceSourceType sourceType;
    private Instant syncedAt;
    @Enumerated(EnumType.STRING)
    private LifecycleStatus status;
    @Type(type = JsonTypes.JSON_BIN)
    @Column(columnDefinition = JsonTypes.JSON_BIN)
    private Attachment attachment;
    @Type(type = JsonTypes.JSON_BIN)
    @Column(columnDefinition = JsonTypes.JSON_BIN)
    private Approval approval;

    public String getSpaceId() {
        return Optional.ofNullable(space)
                .map(SpaceEntity::getId)
                .orElse(null);
    }
}
